package com.aviccxzx.smarthome.fragment;


import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.CamShareActivity;
import com.aviccxzx.smarthome.UserModule.EnterWifiPwdActivity;
import com.aviccxzx.smarthome.UserModule.VideoResetActivity;
import com.aviccxzx.smarthome.adapter.MenuAdapter;
import com.aviccxzx.smarthome.entity.CamBound;
import com.aviccxzx.smarthome.entity.CamExit;
import com.aviccxzx.smarthome.entity.CamListBean;
import com.aviccxzx.smarthome.entity.VideoStatus;
import com.aviccxzx.smarthome.listener.OnItemClickListener;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.netutil.msg.MsgListener;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.utils.NetUtils;
import com.aviccxzx.smarthome.utils.PermissionTool;
import com.aviccxzx.smarthome.video.HmacSHA1Signature;
import com.aviccxzx.smarthome.view.ListViewDecoration;
import com.jovision.sovplay.JVSovPlayActivity;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import zxing.CaptureActivity;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.aviccxzx.smarthome.UserModule.VideoResetActivity.REQUEST_READPHONE_PERM;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.REQUEST_CAMERA_PERM;
import static com.aviccxzx.smarthome.fragment.DeviceListFragment.tagSet;


public class CamFragment extends Fragment implements EasyPermissions.PermissionCallbacks {
    LinearLayout add_cam_ll;

    ImageView add_cam_img;
    SwipeRefreshLayout layout_swipe_refresh;
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";
    /**
     * 扫描跳转Activity RequestCode
     */
    public int REQUEST_VIDEO_CODE = 121;
    public int REQUEST_VIDEOSHARE_CODE = 122;
    boolean hasCam = false;
    String ystno;


    private Activity mContext;
    private MenuAdapter mMenuAdapter;
    private List<String> mStrings;

    private SwipeMenuRecyclerView mSwipeMenuRecyclerView;
    public static List<CamListBean.DataBean> cams = cams = new ArrayList<>();
    ;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.cam_fragment, container, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view = inflater.inflate(R.layout.cam_fragment_v19, container, false);
        }
        return view;

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        spf = getActivity().getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);
        initSwip();
        initView();
        getCamList();
    }

    int pos;

    public void initSwip() {
        mContext = getActivity();
        mSwipeMenuRecyclerView = (SwipeMenuRecyclerView) getView().findViewById(R.id.recycler_view);
        mSwipeMenuRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));// 布局管理器。
        mSwipeMenuRecyclerView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        mSwipeMenuRecyclerView.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画，加也行，不加也行。
        mSwipeMenuRecyclerView.addItemDecoration(new ListViewDecoration());// 添加分割线。

        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        mSwipeMenuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);

        // 设置菜单Item点击监听。
        mSwipeMenuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        mMenuAdapter = new MenuAdapter(cams);
        mMenuAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                //权限判断
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    pos = position;
                    readPhone();
                } else {
                    itemClick(position);
                }
            }
        });
        mSwipeMenuRecyclerView.setAdapter(mMenuAdapter);
    }

    public void itemClick(final int position) {
        String phone_imei = NetUtils.getIMEI(getActivity());
        List<String> phone_ids = cams.get(position).getPhone_ids();
        if (phone_ids != null && phone_ids.contains(phone_imei)) {
            //判断是注册手机
            final ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mobile.getState() == NetworkInfo.State.CONNECTED) {
                //流量能用 wifi不能用 提示用户
                new DialogUtil(getActivity(), true, true, "视频播放会耗费大量流量，建议您关闭流量，使用WIFI播放视频！", "取消提醒", "流量播放", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        //2.视频连接
                        Intent intent = new Intent();
                        intent.putExtra("devNum", cams.get(position).getYst());
                        intent.putExtra("devUser", "admin");
                        intent.putExtra("devPwd", cams.get(position).getUser_pwd());
                        intent.putExtra("devAdmin", cams.get(position).isAdmin());
                        intent.putExtra("version", cams.get(position).getConfigure());
                        intent.setClass(getActivity(), JVSovPlayActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void cancle() {

                    }
                }).showCustomDialog();
            } else {
                //2.视频连接
                Intent intent = new Intent();
                intent.putExtra("devNum", cams.get(position).getYst());
                intent.putExtra("devUser", "admin");
                intent.putExtra("devPwd", cams.get(position).getUser_pwd());
                intent.putExtra("devAdmin", cams.get(position).isAdmin());
                intent.putExtra("version", cams.get(position).getConfigure());
                intent.setClass(getActivity(), JVSovPlayActivity.class);
                startActivity(intent);
            }
        } else {
            App.getApp().showToast("抱歉，您没有观看视频的权限！");
        }
    }

    public void initView() {
        add_cam_ll = (LinearLayout) getView().findViewById(R.id.add_cam_ll);
        add_cam_img = (ImageView) getView().findViewById(R.id.add_cam_img);
        layout_swipe_refresh = (SwipeRefreshLayout) getView().findViewById(R.id.layout_swipe_refresh);
        add_cam_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    cameraTask();
                } else {
                    if (PermissionTool.isCameraCanUse()) {
                        openCamera();
                    } else {
                        // 当前APP没有摄像头权限弹层，或者其他相关提示
                        new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                                .setTitle("权限申请")
                                .setPositiveButton("确认")
                                .setNegativeButton("取消", null /* click listener */)
                                .setRequestCode(REQUEST_CAMERA_PERM)
                                .build()
                                .show();
                    }
                }
            }
        });
        add_cam_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    cameraTask();
                } else {
                    if (PermissionTool.isCameraCanUse()) {
                        openCamera();
                    } else {
                        // 当前APP没有摄像头权限弹层，或者其他相关提示
                        new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                                .setTitle("权限申请")
                                .setPositiveButton("确认")
                                .setNegativeButton("取消", null /* click listener */)
                                .setRequestCode(REQUEST_CAMERA_PERM)
                                .build()
                                .show();
                    }
                }
            }
        });


        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                ystno = (String) args[0];
                if (!TextUtils.isEmpty(ystno)) {
                    //获取摄像头列表
                    getCamList();
                }
            }
        }, "yst");

        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                //密码修改后 更新摄像头列表
                getCamList();
            }
        }, "changeVideoPwd");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                ystno = (String) args[0];
                if (!TextUtils.isEmpty(ystno)) {
                    //分享绑定
                    shareBind(ystno.substring(12, ystno.length()));
                }
            }
        }, "camShare");
        layout_swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getCamList();
                layout_swipe_refresh.setRefreshing(false);
            }
        });
    }

    Timer mtimer = null;

    public void updateCamState() {
        if (mtimer == null) {
            mtimer = new Timer();
        }
        mtimer.schedule(new TimerTask() {
            int i = 120;

            @Override
            public void run() {
                i--;
                if (/*i == 90||*/i == 60 || i == 30) {
                    Looper.prepare();
                    Message message = new Message();
                    message.what = handler_key.UPDATECAM.ordinal();
                    handler.sendMessage(message);
                    Looper.loop();
                } else if (i == 0) {
                    mtimer.cancel();
                }
            }
        }, 0, 1000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mtimer != null) {
            mtimer.cancel();
            mtimer = null;
        }
    }

    private enum handler_key {

        /**
         * 有摄像头
         */
        HAVECAM,

        /**
         * 没有
         */
        NONE,
        /**
         * 定时更新摄像机状态
         */
        UPDATECAM,

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handler_key key = handler_key.values()[msg.what];
            switch (key) {
                case HAVECAM:
                    add_cam_ll.setVisibility(View.GONE);
                    mSwipeMenuRecyclerView.setVisibility(View.VISIBLE);
                    mMenuAdapter.notifyDataSetChanged();
                    break;
                case NONE:
                    //没有摄像头 更新界面
                    add_cam_ll.setVisibility(View.VISIBLE);
                    mSwipeMenuRecyclerView.setVisibility(View.GONE);
                    break;
                case UPDATECAM:
                    getCamList();
                    break;
            }
        }
    };

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.item_height);

            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
            int height = MATCH_PARENT;

            // 添加左侧的，如果不添加，则左侧不会出现菜单。
            //            {
            //                SwipeMenuItem addItem = new SwipeMenuItem(mContext)
            //                        .setBackgroundDrawable(R.drawable.selector_green)// 点击的背景。
            //                        .setImage(R.mipmap.ic_action_add) // 图标。
            //                        .setWidth(width) // 宽度。
            //                        .setHeight(height); // 高度。
            //                swipeLeftMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。
            //
            //                SwipeMenuItem closeItem = new SwipeMenuItem(mContext)
            //                        .setBackgroundDrawable(R.drawable.selector_red)
            //                        .setImage(R.mipmap.ic_action_close)
            //                        .setWidth(width)
            //                        .setHeight(height);
            //
            //                swipeLeftMenu.addMenuItem(closeItem); // 添加一个按钮到左侧菜单。
            //            }

            // 添加右侧的，如果不添加，则右侧不会出现菜单。
            {
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
                        .setBackgroundDrawable(R.drawable.selector_red)
                        .setImage(R.mipmap.delete_icon_red)
                        //                        .setText("解绑") // 文字，还可以设置文字颜色，大小等。。
                        //                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。

                SwipeMenuItem closeItem = new SwipeMenuItem(mContext)
                        .setBackgroundDrawable(R.drawable.selector_red)
                        .setImage(R.mipmap.share_icon)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(closeItem); // 添加一个按钮到右侧菜单。

               /* SwipeMenuItem addItem = new SwipeMenuItem(mContext)
                        .setBackgroundDrawable(R.drawable.selector_green)
                        .setText("添加")
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(addItem); // 添加一个按钮到右侧菜单*/
            }
        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView#RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。

            //            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
            //                Toast.makeText(mContext, "list第" + adapterPosition + "; 右侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
            //            } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
            //                Toast.makeText(mContext, "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
            //            }

            // TODO 如果是删除：推荐调用Adapter.notifyItemRemoved(position)，不推荐Adapter.notifyDataSetChanged();
            if (menuPosition == 0) {// 删除按钮被点击。
                //解除绑定
                unBindCam(cams.get(adapterPosition).getYst(), adapterPosition);
                //解绑成功后执行的操作
                //                mStrings.remove(adapterPosition);
                //                mMenuAdapter.notifyItemRemoved(adapterPosition);
            } else if (menuPosition == 1) {
                if (cams.get(adapterPosition).isAdmin()) {
                    //分享
                    //                    App.getApp().showToast("分享");
                    Intent intent = new Intent(getActivity(), CamShareActivity.class);
                    intent.putExtra("yst", cams.get(adapterPosition).getYst());
                    startActivity(intent);
                } else {
                    App.getApp().showToast("只有管理员才能分享设备");
                }
            }
        }
    };

    public void unBindCam(final String yst, final int pos) {
        showProgressDialog("解绑中...");
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<ResponseBody> call = service.unBindCam(yst);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                disMissDialog();
                //解绑成功后执行的操作
                tagSet.remove(yst);
                JPushInterface.setTags(getActivity(), 0, tagSet);
                cams.remove(pos);
                mMenuAdapter.notifyItemRemoved(pos);
                getCamList();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                disMissDialog();
            }
        });
    }


    public void getCamList() {
        showProgressDialog("加载中...");
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<CamListBean> call = service.getCamlist();
        call.enqueue(new Callback<CamListBean>() {
            @Override
            public void onResponse(Call<CamListBean> call, Response<CamListBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    cams.clear();
                    cams.addAll(response.body().getData());
                    if (cams.size() > 0) {
                        //有摄像头
                        //获取摄像头的在线状态
                        for (int i = 0; i < cams.size(); i++) {
                            getVideoStatus(cams.get(i));
                            tagSet.add(cams.get(i).getYst());
                        }
                        JPushInterface.setTags(getActivity(), 0, tagSet);
                        Message message = new Message();
                        message.what = handler_key.HAVECAM.ordinal();
                        handler.sendMessage(message);
                    } else {
                        disMissDialog();
                        //没有摄像头
                        Message message = new Message();
                        message.what = handler_key.NONE.ordinal();
                        handler.sendMessage(message);
                    }
                }
            }

            @Override
            public void onFailure(Call<CamListBean> call, Throwable t) {
                disMissDialog();
            }
        });
    }

    /**
     * 获取摄像头在线状态
     */
    public void getVideoStatus(final CamListBean.DataBean cam) {
        showProgressDialog("加载中...");
        final String url = "http://avci.soovvi.com/GetDevStatus";
        final String host = "182.92.201.219";
        String accessKeyId = "zhonghangdainzi";
        String accessKeySecret = "123456789";
        final String yst = cam.getYst();

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        final String gmtDate = sdf.format(cd.getTime());

        String signature = HmacSHA1Signature.computeSignature(accessKeySecret, yst + "\n" + gmtDate + "\n");
        final String authorization = accessKeyId + ":" + signature;

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", authorization);
        headers.put("Date", gmtDate);
        headers.put("Host", host);
        headers.put("Yst", yst);
        Map<String, String> params = new HashMap<>();

        //添加请求头拦截器
        Interceptor addHeader = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = new Request.Builder()
                        .url(url)
                        .addHeader("content-type", "application/json")
                        .addHeader("Authorization", authorization)
                        .addHeader("Date", gmtDate)
                        .addHeader("Yst", yst)
                        .build();
                return chain.proceed(request);
            }
        };

        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getStatusServer(addHeader);
        Call<VideoStatus> call = service.GetDevStatus(url);
        call.enqueue(new Callback<VideoStatus>() {
            @Override
            public void onResponse(Call<VideoStatus> call, Response<VideoStatus> response) {
                int online = response.body().getRoot().getOnline();
                if (online == 0) {
                    cam.setOnline("离线");
                    mMenuAdapter.notifyDataSetChanged();
                    updateCamState();
                } else {
                    cam.setOnline("在线");
                    mMenuAdapter.notifyDataSetChanged();
                }
                disMissDialog();
            }

            @Override
            public void onFailure(Call<VideoStatus> call, Throwable t) {
                disMissDialog();
            }
        });
    }


    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 请求操作文件夹权限码
     */

    @AfterPermissionGranted(REQUEST_READPHONE_PERM)
    public void readPhone() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
            // Have permission, do the thing!
            itemClick(pos);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要获取手机状态信息的权限",
                    REQUEST_READPHONE_PERM, Manifest.permission.READ_PHONE_STATE);
        }
    }

    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            if (PermissionTool.isCameraCanUse()) {
                openCamera();
            } else {
                // 当前APP没有摄像头权限弹层，或者其他相关提示
                new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                        .setTitle("权限申请")
                        .setPositiveButton("确认")
                        .setNegativeButton("取消", null /* click listener */)
                        .setRequestCode(REQUEST_CAMERA_PERM)
                        .build()
                        .show();
            }
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求拍照权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //        Toast.makeText(getActivity(), "执行onPermissionsGranted()...", Toast.LENGTH_SHORT).show();
        //        openCamera();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //        Toast.makeText(getActivity(), "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
        switch (requestCode) {
            case REQUEST_CAMERA_PERM:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this, getActivity().getResources().getString(R.string.camera_show))
                            .setTitle("权限申请")
                            .setPositiveButton("确认")
                            .setNegativeButton("取消", null /* click listener */)
                            .setRequestCode(REQUEST_CAMERA_PERM)
                            .build()
                            .show();
                }
                break;
            case REQUEST_READPHONE_PERM:
                if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
                    new AppSettingsDialog.Builder(this, getActivity().getResources().getString(R.string.readphone_show))
                            .setTitle("权限申请")
                            .setPositiveButton("确认")
                            .setNegativeButton("取消", null /* click listener */)
                            .setRequestCode(REQUEST_READPHONE_PERM)
                            .build()
                            .show();
                }
                break;
        }
    }

    private void openCamera() {
        Intent intent = new Intent(getActivity().getApplication(), CaptureActivity.class);
        intent.putExtra("from", "video");
        startActivityForResult(intent, REQUEST_VIDEO_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_VIDEO_CODE) {

            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                spf.edit().putString("type", "").commit();
                String videoCode = bundle.getString("mac", "");
                if (!TextUtils.isEmpty(videoCode)) {
                    //查询是否是分享摄像头
                    if (videoCode.contains("cameraShare")) {
                        //分享摄像头
                        //分享绑定
                        shareBind(videoCode.substring(12, videoCode.length()));
                    } else if (videoCode.contains("C")) {
                        //猫眼相机
                        Intent intent = new Intent(getActivity(), EnterWifiPwdActivity.class);
                        //0 0 C20211208600121-831485
                        intent.putExtra("video", "video");
                        spf.edit().putString("yst", videoCode.substring(2,12)).commit();
                        spf.edit().putString("type", "cat").commit();
                        startActivity(intent);
                    } else {
                        //查询是否是有效摄像头
                        //H12345678A
                        //H123456789B
                        if (!videoCode.contains("A") && !videoCode.contains("B")) {
                            CheckDevExist(videoCode);
                        } else {
                            CheckDevExist(videoCode.substring(0, videoCode.length() - 1));
                        }
                        //判断高低版本
                        boolean standard = false;
                        if (videoCode.contains("A")) {
                            standard = false;
                        } else {
                            standard = true;
                        }
                        spf.edit().putBoolean("standard", standard).commit();
                    }
                } else {
                    App.getApp().showToast("请扫描正确的二维码");
                }
            }
        }
    }

    /**
     * 分享绑定摄像头
     */
    public void shareBind(String yst) {
        showProgressDialog("加载中...");
        String phone_imei = NetUtils.getIMEI(getActivity());
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<ResponseBody> call = service.shareBindCam(yst, phone_imei);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                disMissDialog();
                getCamList();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                disMissDialog();
            }
        });
    }

    /**
     * 获取摄像头有效性
     */
    public void CheckDevExist(final String ystno) {
        showProgressDialog("加载中...");
        final String url = "http://avci.soovvi.com/CheckDevExist";
        //String host = "xwdev.soovvi.com";
        final String host = "182.92.201.219";
        String accessKeyId = "zhonghangdainzi";
        String accessKeySecret = "123456789";
        final String yst = ystno;

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        final String gmtDate = sdf.format(cd.getTime());

        String signature = HmacSHA1Signature.computeSignature(accessKeySecret, yst + "\n" + gmtDate + "\n");
        final String authorization = accessKeyId + ":" + signature;

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", authorization);
        headers.put("Date", gmtDate);
        headers.put("Host", host);
        headers.put("Yst", yst);
        Map<String, String> params = new HashMap<>();

        //添加请求头拦截器
        Interceptor addHeader = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = new Request.Builder()
                        .url(url)
                        .addHeader("content-type", "application/json")
                        .addHeader("Authorization", authorization)
                        .addHeader("Date", gmtDate)
                        .addHeader("Yst", yst)
                        .build();
                return chain.proceed(request);
            }
        };

        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getStatusServer(addHeader);
        Call<CamExit> call = service.CheckDevExist(url);
        call.enqueue(new Callback<CamExit>() {
            @Override
            public void onResponse(Call<CamExit> call, Response<CamExit> response) {
                int online = response.body().getRoot().getExist();
                if (online == 0) {
                    //无效设备
                    App.getApp().showToast(ystno + "设备无效");
                    disMissDialog();
                } else {
                    //有效设备
                    //1.查询设备是否在线 在线就直接走机智云绑定，离线走配网流程
                    //                    getCamStatus(ystno);
                    //2.调用机智云接口查询该摄像头是否被添加了,如果被添加则提示无法添加
                    camisBound(ystno);
                }
            }

            @Override
            public void onFailure(Call<CamExit> call, Throwable t) {
                disMissDialog();
            }
        });
    }

    public void camisBound(final String yst) {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<CamBound> call = service.camisBound(yst);
        call.enqueue(new Callback<CamBound>() {
            @Override
            public void onResponse(Call<CamBound> call, Response<CamBound> response) {
                int code = response.body().getCode();
                if (code == 200) {
                    //已经被绑定，提示用户已经被绑定
                    App.getApp().showToast("设备" + yst + "已经被绑定");
                    disMissDialog();
                } else if (code == 201) {
                    //设备在线状态
                    //修改为每次添加摄像机时都要走绑定流程
                    Intent intent = new Intent(getActivity(), VideoResetActivity.class);
                    intent.putExtra("yst", yst);
                    startActivity(intent);
                    disMissDialog();
                }

            }

            @Override
            public void onFailure(Call<CamBound> call, Throwable t) {
                App.getApp().showToast("查询失败，请稍后重试");
                disMissDialog();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
